﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Cc9d {
	public  class IdReader {
		public const string Readme = 
			"IdReader 读取对方的身份ID。\n" +
			"发送一个转义命令，0x90，会收到一批转义命令，范围在0xd0到0xfa之间以，以0xfa结尾，构成对方的身份ID。\n" +
			"使用时请确保对方设备支持此功能。";


		static readonly char[] IdCharMap = new char[]{
			// 0xd0 - 0xd9: '0'~'9'
			'0','1','2','3','4','5','6','7','8','9',
			// 0xda - 0xf3: 'A'~'Z'
			'A','B','C','D','E','F','G','H','I','J','K','L','M',
			'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
			// 0xf4 - 0xf9: 6个自定义符号，可按实际协议定义
			'-','_','.','@','#','*'
			// 0xfa: 结束符，不做映射
		};


		public static string getId(Cc9dCodec c) {
			if (c.dRecvEcmd != null) {
				throw new InvalidOperationException("使用这个功能会占用解码器的dRecvEcmd，但是这个回调函数已经被占用了。");
			}
			List<byte> id_bytes = new List<byte>(16);
			using (AutoResetEvent handshake_recv_event = new AutoResetEvent(false)) {
				c.dRecvEcmd = (byte b) => {
					if (b == 0xfa) {
						c.dRecvEcmd = null; // 清除回调
						handshake_recv_event?.Set();
						return;
					}
					if (b >= 0xd0 &&  b < 0xfa) {
						id_bytes.Add(b);
					}
				};
				c.sendEcmd(0x90);
				if (handshake_recv_event.WaitOne(100) == true) {
					c.dRecvEcmd = null; 
					return new string(id_bytes.Select(b => IdCharMap[b - 0xd0]).ToArray());
				} else {
					c.dRecvEcmd = null;
					return null;
				}

			}

		}
	}
}
